package com.blb.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WaitDemo2 {

    private Lock lock = new ReentrantLock();
    //Condition对象
    private Condition condition = lock.newCondition();

    public void testWait(){
        lock.lock();
        try {
            System.out.println( Thread.currentThread().getName() + "执行testWait，等待");
            //锁可以调用wait
            condition.await();
            System.out.println(Thread.currentThread().getName() + "结束testWait");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void testNotify(){
        lock.lock();
        try {
            //通知线程
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args){
        WaitDemo2 demo = new WaitDemo2();
        //子线程等待
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                demo.testWait();
            }).start();
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //主线程通知子线程
        demo.testNotify();
    }
}
